<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\controller\Util;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 学生评论管理
 *
 * @icon fa fa-circle-o
 */
class CommUser extends Backend
{

    /**
     * CommUser模型对象
     * @var \app\admin\model\CommUser
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\CommUser;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("appliedList", $this->model->getAppliedList());
    }
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $wheres = [];
            if ($this->auth->id !== 1) {
                //  只展示老师自己课程下的评论
                $teacherInfo = Util::getUserInfo($this->auth->id, 'admin_id');
                $courses = Db::name('course')->where('teacher_id', $teacherInfo['id'])->field('id')->select();
                $coursesIds = array_column((array)$courses, 'id');
                $wheres = [
                    'fid' => ['in', $coursesIds]
                ];
            }
            $wheres['pid'] = 0 ;

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['course'])
                ->where($where)->where($wheres)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['course'])
                ->where($where)->where($wheres)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $row) {
                $row->visible(['id', 'uid', 'uname', 'content', 'time', 'applied', 'status', 'type', 'fid', 'remark', 'level', 'pid']);
                $row->visible(['course']);
                $row->getRelation('course')->visible(['title']);
                $row['level'] = str_repeat("★",$row['level']);
            }
            $list = collection($list)->toArray();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add($ids = '')
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));

                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    //这里是老师的回复|需要添加一些对应的字段
                    $teacherInfo = Util::getUserInfo($this->auth->id, 'admin_id');
                    $params['uid'] = $teacherInfo['id'];
                    $params['uname'] = $teacherInfo['nick_name'];
                    $params['uname'] = $teacherInfo['nick_name'];
                    $params['pid'] = $ids;
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    public function show($ids = ''){
        $row = Db::name('comm_user')->alias('cu')
            ->join('student s','cu.uid = s.id')
            ->where('cu.id',$ids)
            ->field('s.nick_name,s.header_image,cu.*')
            ->find();
        $teacher = Db::name('comm_user')->alias('cu')
            ->join('teacher t','cu.uid = t.id')
            ->where('cu.pid',$row['id'])
            ->field('t.nick_name,t.header,cu.*')
            ->find();
        $title = Db::name('course')->where('id',$row['fid'])->field('title')->find()['title'];
        $data = [
            'student' => $row,
            'teacher' => $teacher,
            'title' => $title,
        ];
        $this->assign('data',$data);
        return $this->view->fetch();
    }
}
